package controller

import (
	"github.com/gin-gonic/gin"
	"honeyweb/lib"
	"honeyweb/log"
	"honeyweb/middleware"
	"honeyweb/model"
	"net/http"
)

//以jsonrpc 结构请求的处理 模板
type LoginController struct {
	HandlerMap map[string]lib.ClientHanlder
}

func NewLoginController() *LoginController {
	ct :=  &LoginController{
		HandlerMap: make(map[string]lib.ClientHanlder),
	}

	//根据业务修改
	ct.HandlerMap["login.login"] = ct.Login

	return ct
}

func RegisterLoginRoute(group *gin.RouterGroup) {
	ct := NewLoginController()
	g := group.Group("")
	g.POST("/login", ct.HttpHandler)
}

func (ct *LoginController)GetHandlerByMethod(method string) lib.ClientHanlder {
	handler, ok := ct.HandlerMap[method]
	if ok {
		return handler
	}
	return nil
}

//根据jsonrpc 的请求参数找到对应的处理函数处理
func (ct *LoginController) HttpHandler(c *gin.Context) {
	var req model.JsonReq
	c.ShouldBindJSON(&req)
	uid := c.GetInt("uid")
	handler := ct.GetHandlerByMethod(req.Method)
	var resp *model.JsonResp
	if handler != nil {
		result, err := handler(uid,  &req)
		if err == nil {
			str := model.Encode2String(result)
			resp = model.NewResultResp(req.Id, req.Method, str)
		} else if err != nil{
			resp = model.NewErrJsonResp(req.Id,req.Method, model.E_SERVER, err.Error())
		}
	}
	c.JSON(http.StatusOK, resp)
}

//////////////////////////////////
///	//根据业务修改
/////////////////////////////////
func (ct *LoginController) Login(uid int, req *model.JsonReq) (interface{}, error){
	var params model.LoginReq
	model.DecodeFromString(req.Params, &params)

	var resp model.LoginResp
	resp.Token = middleware.CreateAccountToken(uid)
	log.S().Debugf("user: %d get login req:%+v resp:%+v", params, resp )
	return &resp, nil
}

